package ru.hh.school.logging;

import ru.hh.school.util.BlockingQueue;

public class ThreadLogger implements Logger, Runnable {
    private final Logger mainLogger;
    private final BlockingQueue<Object> logQueue;

    public ThreadLogger(int logQueueLength, Logger logger) {
        this.mainLogger = logger;
        logQueue = new BlockingQueue<Object>(logQueueLength);
        Thread thread = new Thread(this);
        thread.start();
    }

    public void log(String message) {
        logQueue.add(message);
    }

    public void logError(Exception exception) {
        logQueue.add(exception);
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                Object tolog = logQueue.take();
                if (tolog instanceof Exception) {
                    mainLogger.logError((Exception) tolog);
                } else {
                    mainLogger.log(tolog.toString());
                }
            }
        } catch (InterruptedException e) {
            //ignore
        }
    }
}
